<template>
  <div class="count-down">
    <span class="time-block">{{ days }}</span>
    <span class="time-separator">天</span>
    <span class="time-block">{{ hours }}</span>
    <span class="time-separator">:</span>
    <span class="time-block">{{ minutes }}</span>
    <span class="time-separator">:</span>
    <span class="time-block">{{ seconds }}</span>
  </div>
</template>

<script>
export default {
  name: 'CountDown',
  props: {
    time: {
      type: Number,
      required: true
    },
    format: {
      type: String,
      default: 'DD:HH:mm:ss'
    },
    autoStart: {
      type: Boolean,
      default: true
    },
    onEnd: {
      type: Function,
      default: () => {}
    }
  },
  data() {
    return {
      days: '00',
      hours: '00',
      minutes: '00',
      seconds: '00',
      timer: null,
      endTime: 0
    }
  },
  watch: {
    time: {
      handler(val) {
        this.reset(val)
      },
      immediate: true
    }
  },
  mounted() {
    if (this.autoStart) {
      this.start()
    }
  },
  beforeDestroy() {
    this.stop()
  },
  methods: {
    start() {
      if (this.timer) {
        return
      }
      
      this.endTime = Date.now() + this.time
      
      this.timer = setInterval(() => {
        const remaining = this.endTime - Date.now()
        
        if (remaining <= 0) {
          this.days = '00'
          this.hours = '00'
          this.minutes = '00'
          this.seconds = '00'
          this.stop()
          this.onEnd()
          return
        }
        
        this.updateTime(remaining)
      }, 1000)
    },
    stop() {
      if (this.timer) {
        clearInterval(this.timer)
        this.timer = null
      }
    },
    reset(time) {
      this.stop()
      this.updateTime(time)
      
      if (this.autoStart) {
        this.start()
      }
    },
    updateTime(time) {
      const days = Math.floor(time / (1000 * 60 * 60 * 24))
      const hours = Math.floor((time % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
      const minutes = Math.floor((time % (1000 * 60 * 60)) / (1000 * 60))
      const seconds = Math.floor((time % (1000 * 60)) / 1000)
      
      this.days = days < 10 ? `0${days}` : `${days}`
      this.hours = hours < 10 ? `0${hours}` : `${hours}`
      this.minutes = minutes < 10 ? `0${minutes}` : `${minutes}`
      this.seconds = seconds < 10 ? `0${seconds}` : `${seconds}`
    }
  }
}
</script>

<style lang="scss" scoped>
.count-down {
  display: inline-flex;
  align-items: center;
  
  .time-block {
    display: inline-block;
    min-width: 24px;
    padding: 0 4px;
    text-align: center;
    font-family: monospace;
    font-weight: bold;
  }
  
  .time-separator {
    margin: 0 2px;
  }
}
</style> 